package com.hdu.careerplan.util;

import com.hdu.careerplan.enums.CommandPatternEnum;

import java.io.*;
import java.nio.charset.StandardCharsets;

import static com.hdu.careerplan.configuration.PythonTypeConfig.*;


public class PythonProcessUtil {



    /**
     * 拼接python命令字符串
     * @param dirPath    代码文件位置，末尾不写‘\’
     * @param pythonName 文件名
     * @param argModel   枚举包含的参数模样，例如：-c -o
     * @param args       具体参数值
     * @return 不合要求返回null，正确返回命令行
     */
    //TODO ZHR [2023.12.27] 修改为添加列表参数
    public static String generatePythonCommand(String dirPath, String pythonName, CommandPatternEnum argModel, String... args) {
        if (argModel.getArgList().isEmpty()) { // 没有外设参数表，直接传参数
            StringBuilder stringBuilder = new StringBuilder(COMMAND_HEAD);
            stringBuilder.append(" ").append(dirPath).append(DIR_TYPE).append(pythonName);
            for (String arg : args) {
                stringBuilder.append(" ").append(arg);
            }
            return stringBuilder.toString();

        } else if (argModel.getArgList().size() != args.length) return null; // 参数不匹配，返回null

        StringBuilder stringBuilder = new StringBuilder(COMMAND_HEAD);
        stringBuilder.append(" ").append(dirPath).append(DIR_TYPE).append(pythonName);
        for (int i = 0; i < argModel.getArgList().size(); i++) {
            stringBuilder.append(" ").append(argModel.getArgList().get(i)).append(" ").append(args[i]);
        }
        return stringBuilder.toString();

    }

    //TODO ZHR 2023.12.12 对启动python进程的优化
    public static String startPythonProcess(String command) throws IOException, InterruptedException {
        System.out.println(command);
        StringBuilder output = new StringBuilder();
        final Process process = Runtime.getRuntime().exec(command);
        try (BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream(), CHARSET_NAME))) {
            System.out.println("------------------------------");
            System.out.println("start");
            String line;
            while ((line = br.readLine()) != null) {
                try {
                    process.exitValue();
                    break; // exitValue没有异常表示进程执行完成，退出循环
                } catch (IllegalThreadStateException e) {
                    // 异常代表进程没有执行完
//                    System.out.print("-");
                }
                //此处只做输出，对结果有其他需求可以在主线程使用其他容器收集此输出
//                System.out.println(line);
                output.append(line);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        process.waitFor();
        System.out.println(output);
        System.out.println("------------------------------");
        return output.toString();
    }


}
